package handler

import (
	"encoding/json"

	"github.com/Shopify/sarama"
	"time"
	"week13/errors"
	"week13/internal/biz/item"
	"week13/log"
)
//商品变动job
type SyncItemToCache struct {
}
func (SyncItemToCache) Setup(_ sarama.ConsumerGroupSession ) error   { return nil }
func (SyncItemToCache) Cleanup(_ sarama.ConsumerGroupSession ) error { return nil }
func (sycache SyncItemToCache) ConsumeClaim(sess sarama.ConsumerGroupSession , claim sarama.ConsumerGroupClaim) error {
	for msg := range claim.Messages() {
		log.Info("*******Message topic:%q partition:%d offset:%d\n", msg.Topic, msg.Partition, msg.Offset)
		err := sycache.Run(msg.Value)
		if err !=nil {
			log.Error("deal msg:%+v,err:%s",msg,err.Error())
		}
		sess.MarkMessage(msg, "")
	}
	return nil
}
type SyncItemMessege struct {
	ItemId int
}
func (sycache *SyncItemToCache) Run(jsonData []byte) error {
	if len(jsonData) <1{
		return errors.NewIllegalParam("参数错误")
	}
	msg := SyncItemMessege{}
	err := json.Unmarshal(jsonData,&msg)
	if err != nil {
		return errors.NewIllegalParam(err.Error())
	}
	if msg.ItemId < 1{
		return errors.NewIllegalParam("ItemId < 1")
	}
	cacheDTO, err := item.FindItemFromCache(msg.ItemId)
	if err != nil{
		return err
	}
	realDTO,err := item.FindOne(item.ItemDTO{ItemId: msg.ItemId})
	if err != nil {
		return err
	}
	realTm, _ := time.Parse("2006-01-02 15:04:05", realDTO.Mtime)
	cacheTm, _ := time.Parse("2006-01-02 15:04:05", cacheDTO.Mtime)
	if realTm.Unix()<cacheTm.Unix() {
		log.Info("%d nothing change",msg.ItemId)
		return nil
	}
	item.SetItemToCache(realDTO)
	return nil
}


